package com.company.笔试.链表减法;



import java.util.ArrayList;

/**
 * @Classname linkListSub
 * @Description TODO
 * @Date 2021/10/5 20:57
 * @Created by ylr
 */




public class linkListSub {
    private static ArrayList<Integer> resList = new ArrayList<>();

    public static void main(String[] args) {
        ListNode l1 = new ListNode(7);
        l1.next = new ListNode(8);
        l1.next.next = new ListNode(4);
        l1.next.next.next = new ListNode(4);
        l1.next.next.next.next = new ListNode(4);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(2);
        l2.next.next = new ListNode(3);

        ListNode res = getRes(l1, l2);
        System.out.println("---------列表结果打印--------------");
        resList.forEach(System.out::println);
        System.out.println("---------链表结果打印--------------");
        while (res!=null){
            int val = res.val;
            System.out.println(val);
            res = res.next;
        }

    }

    public static ListNode getRes(ListNode l1, ListNode l2){
        Sub(l1,l2);
        ListNode res = new ListNode(-1);
        ListNode tmp = res;//操作指针
        if (resList.get(resList.size()-1)==0){ //列表尾部是最高位为0 这个数为0
            return new ListNode(0);
        }
        boolean flag = true;
        for (int num: resList){
            if (num>=0){
                tmp.next = new ListNode(num);
                tmp = tmp.next;
            }else {//-1代表负数
                flag =false;
                break;
            }
        }
        return flag?res.next:res;

    }




    /*
       求差
       个位在首
       负数返回-1

     */
    public static void Sub(ListNode l1, ListNode l2) {
        if (l1 == null && l2 != null) {
            resList.clear();
            resList.add(-1);
            return;
        }
        if (l1 == null && l2 == null) {
            return;
        }
        if (l1 != null && l2 == null) {
            while (l1!=null){
                resList.add(l1.val);
                l1 = l1.next;
            }
            return;
        }
        int num1 = l1.val;
        int num2 = l2.val;
        int tmp = num1 - num2;
        if (tmp >= 0) {
            resList.add(tmp);
            Sub(l1.next, l2.next);
        } else if (l1.next != null) {
            resList.add(tmp + 10);
            l1.next.val -= 1;
            Sub(l1.next, l2.next);
        } else {
            resList.clear();
            resList.add(-1);
            return;
        }
    }


}
